﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Engine.Entities.Character;
using FrenzyIsland.UI;

public class UIMenuCharactersCtrl : MonoBehaviour {

    public UIGrid grid;
    public UIScrollView scrollview;
    public GameObject UICharacterItem;

    /* Controlli */
    public UILabel LblName;
    public UILabel LblSurname;
    public UILabel LblJob;

    private List<GameObject> ListCharacter = new List<GameObject>();
    private int cont = 0;

    private const int START_OFFSET_X = -660;
    private const int COL_WIDTH = 350;
    private const int ROW_HEIGHT = 200;
    private const int COLS = 2;

    private FrenzyPeopleController peopleCtrl;
    private GuiManager guiManager;

    void Awake() 
    {
        peopleCtrl = GameObject.FindGameObjectWithTag("VoxelWorld").GetComponent<FrenzyPeopleController>();
        guiManager = GameObject.FindGameObjectWithTag("UI").GetComponent<GuiManager>();

        Debug.Assert(peopleCtrl != null, "Non sono riuscito a prendere il ctrl");
        Debug.Assert(guiManager != null, "Non sono riuscito a prendere GuiManager");
    }

	void Start () {}
	
	void Update () {
	
	}

    public void Close()
    {
        //guiManager.CloseMenu(this.gameObject);
    }

    internal void LoadPeople()
    {
        Debug.Assert(peopleCtrl != null, "Il controller è null!!!" );

        clearPeople();

        Debug.Log("Carico " + peopleCtrl.SteveList.Count + " oggetti");
        cont = 0;

        foreach (SteveBrain item in peopleCtrl.SteveList)
        {
            GameObject newItem = AddItem(item);
            ListCharacter.Add(newItem); //copia il riferimento del nuovo oggetto creato
            cont++;
        }

        //grid.Reposition();
        //grid.repositionNow = true;
        scrollview.ResetPosition();
        //scrollview.RestrictWithinBounds(true);
    }

    private void clearPeople()
    {
        foreach (GameObject item in ListCharacter)
        {
            DestroyImmediate(item);
        }
    }

    public GameObject AddItem(SteveBrain brain, string name = null)
    {
        GameObject newChar = Instantiate(UICharacterItem);

        newChar.transform.parent = grid.transform;
        newChar.transform.localScale = new Vector3(1, 1, 1);
        newChar.transform.localPosition = new Vector3(0, 0, 0);

        newChar.GetComponent<UICharacterItem>().SteveBrain = brain;

        return newChar;
    }

    public void PeopleClick(GameObject gameObject)
    {
        SteveModel model = gameObject.GetComponent<UICharacterItem>().SteveModel;
        
        if (model == null) return;

        LblName.text = model.Name;
        LblSurname.text = model.Surname;
        LblJob.text = model.JobName;
    }
}
